import 'dart:async';
import 'dart:ui';

import 'package:acgn_pioneer/pages/sendsms/sendsms_mixin.dart';
import 'package:acgn_pioneer/plugin/flutter_verification/index.dart';
import 'package:flutter/material.dart';
import '../public.dart';

const $COUNT_DOWN_TIME = 60;

/// 我的页面
class VerificationCodePage extends StatefulWidget {
  final Map<String, dynamic> params;
  VerificationCodePage(this.params, {Key key}) : super(key: key);

  @override
  _VerificationCodePageState createState() {
    return _VerificationCodePageState();
  }
}

class _VerificationCodePageState extends State<VerificationCodePage>
    with SendSMSMixin<VerificationCodePage> {
  ThemeProvider theme;
  Timer _timer;
  int _countdownTime = $COUNT_DOWN_TIME;
  LoginPage loginPage;

  @override
  void initState() {
    super.initState();
    dialCode = widget.params['dialCode'][0];
    phone = widget.params['phone'][0];
    startCountdownTimer();
  }

  @override
  Widget build(BuildContext context) {
    theme = Provider.of<ThemeProvider>(context);
    loginPage = LoginPage(context, size: MediaQuery.of(context).size);
    return Scaffold(
        backgroundColor: theme.primaryColor,
        appBar: AppBar(
          // title: Text('验证码校验'),
          leadingWidth: 44,
          leading: BackComponent(),
        ),
        body: SingleChildScrollView(
            child: Padding(
                padding: EdgeInsets.only(left: 16, top: 64, right: 16),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '验证码已发送至',
                        style: TextStyle(fontSize: 28, color: Colors.white),
                      ),
                      SizedBox(
                        height: 16,
                      ),
                      Text(
                        '$dialCode $phone',
                        style: TextStyle(fontSize: 14, color: Colors.white),
                      ),
                      SizedBox(
                        height: 32,
                      ),
                      VerificationBox(
                          width: 44,
                          height: 56,
                          cursorColor: Colors.white,
                          textStyle:
                              TextStyle(color: Colors.white, fontSize: 18),
                          decoration: BoxDecoration(
                              color: ColorUtil.rgba(255, 255, 255, 0.15),
                              border: Border.all(width: 0),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8))),
                          maxLength: 6,
                          onChanged: (v) {
                            UserService.mobilebind({
                              'mobile': widget.params['phone'][0],
                              'vcode': v
                            }).then((res) {
                              if (res['status'] != 0) {
                                ACGN.toast.message(res['msg']);
                              } else {
                                MobileBindModel user = res['data'];
                                LogUtil.e(user, tag: 'MobileBindModel');
                                _userLogin(user);
                              }
                            });
                          }),
                      SizedBox(
                        height: 40,
                      ),
                      FlatButton(
                          onPressed:
                              _countdownTime < 1 ? () => sendsms() : null,
                          height: 48,
                          minWidth: double.infinity,
                          textColor: ColorUtil.rgba(51, 51, 51, 1),
                          shape: RoundedRectangleBorder(
                              side: BorderSide.none,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(24))),
                          color: ColorUtil.rgba(255, 215, 59, 1),
                          disabledColor: ColorUtil.rgba(255, 215, 59, 0.15),
                          child: Text(
                            _countdownTime > 0
                                ? '$_countdownTime秒后可重新获取'
                                : '重新发送验证码',
                            style: TextStyle(fontSize: 18),
                          ))
                    ]))));
  }

  void startCountdownTimer() {
    const oneSec = const Duration(seconds: 1);
    _timer = Timer.periodic(oneSec, (timer) {
      setState(() {
        if (_countdownTime < 1) {
          _timer.cancel();
        } else {
          --_countdownTime;
        }
      });
    });
  }

  _userLogin(MobileBindModel mobileBindInfo) async {
    var deviceInfo = await PlatformUtil.getDeviceInfo();
    String deviceId = deviceInfo[2];
    await loginPage.login(
        {'type': 'mkxq', 'device': deviceId, 'token': mobileBindInfo.appToken}, false);
    Routers.navigateTo(RouterPage.MY_INDEX, replace: true);
  }

  callbackSMS() {
    // 重置倒计时
    setState(() {
      _countdownTime = $COUNT_DOWN_TIME;
    });
    startCountdownTimer();
  }

  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }
}
